# @Time : 2020/9/8 10:10
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np
import imutils

# 读取目标图片
target = cv.imread("match01.png", cv.IMREAD_GRAYSCALE)
clone = target.copy()
# 读取模板图片
template = cv.imread("target.png", cv.IMREAD_GRAYSCALE)
# 获取模板图片的高宽尺寸
temHeight, temWidth = template.shape[:2]
print(temWidth, temHeight)
# 执行模板匹配
result = cv.matchTemplate(target, template, cv.TM_CCOEFF_NORMED)
minVal, maxVal, minLoc, (x, y) = cv.minMaxLoc(result)
cv.rectangle(target, (x, y), (x + temWidth, y + temHeight), 125, 2)
mask = np.zeros(target.shape, dtype=np.uint8)
cv.rectangle(mask, (x, y), (x + temWidth, y + temHeight), 255, -1)
resTarget = cv.bitwise_and(target, target, mask=mask)
cv.imshow("ResultTarget", resTarget)
cv.imshow("Target", target)
cv.imshow("Template", template)

# 将截取的矩形提取出来
resTarget = target[y:y + temHeight, x:x + temHeight]

targetBlurred = cv.medianBlur(resTarget, 5)
cv.imshow("TargetBlurred", targetBlurred)

ret, threshold = cv.threshold(targetBlurred, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
cv.imshow("Threshold", threshold)
cv.waitKey(0)

kernel = (5, 5)
erosion = cv.erode(threshold, kernel, iterations=1)
dilation = cv.dilate(erosion, kernel, iterations=1)
cv.imshow("Dilation", dilation)
cv.waitKey(0)

canny = cv.Canny(erosion, 30, 100)
cv.imshow("Canny", canny)
cv.waitKey(0)
circles = cv.HoughCircles(canny, cv.HOUGH_GRADIENT, 1, 80, param1=100, param2=20, minRadius=1, maxRadius=10)

p = circles[0]  # 去掉circles数组一层外括号
for i in p:
    cv.circle(resTarget, (i[0], i[1]), i[2], (0, 255, 0), 2)
    cv.circle(resTarget, (i[0], i[1]), 1, (0, 0, 255), -1)

cv.imshow("Circle", resTarget)
cv.waitKey(0)
